import React from 'react';
import { useHistory, useParams } from 'react-router-dom/cjs/react-router-dom';
import { useState, useContext, useEffect } from 'react';
import api from './api/api';
import DataContext from './context/DataContext';
import DescriptionCard from './DescriptionCard';
import PodcastCard from './PodcastCard';
import placeholder from './assets/placeholder_240x240.png';

const User = () => {

  const { id } = useParams();
  const history = useHistory();

  const { baseUrl, loginUserId, logout } = useContext(DataContext);
  const [user, setUser] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [podcasts, setPodcasts] = useState([]);

  const handleEdit = () => {
    history.push('/edit-user');
  };

  const handleLogout = () => {
    logout();
  };

  const handlePost = () => {
    history.push(`/post-podcast`);
  };

  useEffect(() => {
    const getUser = async () => {
      try {
        const meResponse = await api.get(`/users/${id}`);
        const returnedUser = meResponse.data;
        returnedUser.avatarUrl = `${baseUrl}/users/${returnedUser.id}/avatar`;
        setUser(returnedUser);
        const podcastsResponse = await api.get(`/users/${returnedUser.id}/podcasts`);
        let returnedPodcasts = podcastsResponse.data;
        returnedPodcasts = returnedPodcasts.map((podcast) => {
          podcast.coverUrl = `${baseUrl}/podcasts/${podcast.id}/cover`;
          return podcast;
        });
        setPodcasts(returnedPodcasts);
        setIsLoading(false);
      } catch (error) {
        console.log(error);
      }
    };
    getUser();
  }, [id, baseUrl]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container">
        <h1 className='mt-2 mb-5'>用户信息</h1>
        {!isLoading && <>
          <div className="row">
            <div className="col-lg-4 col-sm d-flex justify-content-center align-items-center">
              <img src={user.avatarUrl} onError={(e) => e.target.src = placeholder} className="img-thumbnail mb-3" alt="..." />
            </div>

            <div className='col-lg-7 col-sm text-center d-flex flex-column justify-content-center align-items-end'>
              <table className="table table-bordered table-hover">
                <tbody>
                  <tr>
                    <th scope="row">昵称</th>
                    <td>{user.nickname}</td>
                  </tr>
                  <tr>
                    <th scope="row">用户名</th>
                    <td>{user.username}</td>
                  </tr>
                  <tr>
                    <th scope="row">邮箱</th>
                    <td>{user.email}</td>
                  </tr>
                  <tr>
                    <th scope="row">专辑数量</th>
                    <td>{podcasts.length}</td>
                  </tr>
                  <tr>
                    <th scope="row">注册日期</th>
                    <td>{user.createtime.slice(0, 16)}</td>
                  </tr>
                </tbody>
              </table>
              {user.id === loginUserId &&
                <div>
                  <button className="btn btn-sm btn-outline-primary mx-1" onClick={handlePost}>新建</button>
                  <button className="btn btn-sm btn-outline-primary mx-1" onClick={handleEdit}>编辑</button>
                  <button className="btn btn-sm btn-outline-primary mx-1" onClick={handleLogout}>退出</button>
                </div>
              }
            </div>
          </div>
          <h2 className='my-3'>个人简介</h2>
          <DescriptionCard text={user.description} />
          <h2 className='my-3'>播客专辑</h2>
          <div className="row justify-content-start">
            {podcasts.map((podcast) => (
              <PodcastCard key={podcast.id} id={podcast.id} title={podcast.title} coverUrl={podcast.coverUrl} />
            ))}
          </div>
        </>
        }
      </div>
      <div className="my-3"></div>
    </div >
  );
};

export default User;
